<template>
    <div class="page">
        <div class="build-tag-btn" @click="switchBuildingTagPopup">
            <img class="icon-building" src="@/assets/img/building.png"/>
            <span>楼盘物理标签</span>
            <img class="icon-arrow" src="@/assets/img/arrow.png"/>
        </div>
        <xc-map
            query-type="tag"
            :query-province="tagQueryData.provinceList"
            :query-city="tagQueryData.cityList"
            @get-city-premises-list="getCityPremisesList"
        ></xc-map>
        <div class="page-bottom">
            <resource-info
                :detail="mediaResourceInfo"
                type="tag"
            ></resource-info>
            <div class="btn-box">
                <div class="pre-btn" @click="goPre">
                    <span>上一步</span>
                </div>
                <div class="next-btn" @click="goNext">
                    <span>下一步</span>
                </div>
            </div>
        </div>
        <building-tag
            :show-action="buildingTagPopupShow"
            @close="switchBuildingTagPopup"
            @confirm="onBuildingTagConfirm"
        ></building-tag>
    </div>
</template>

<script lang="ts" name="selectByTagMap" setup>
import {onMounted, ref, reactive, computed} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {store} from '@/store';
import XcMap from '@/components/XCMap/index.vue';
import ResourceInfo from '@/views/products/components/ResourceInfo.vue';
import BuildingTag from '@/components/BuildTag/index.vue';
import {Premises, Province, City} from '@/components/XCMap/types';
import {MediaResourceInfo} from '@/views/products/components/ResourceInfo.vue';
import {getTagQueryData, getBuildingTagQueryData} from '@/api/selectByTag';
import { clearLoading, showLoading } from '@/api';

interface Tag {
    id: number;
    pid: number;
    tgCode: string;
}
interface TagQueryForm {
    projectId: number;
    cityCodes: Array<string>;
    tags: Array<string>;
    premisesTypes: Array<string>;
    premisesPrices: Array<number>;
    premisesAges: Array<number>;
    inHouseRates: Array<number>;
    parkingNums: Array<number>;
    propertyFees: Array<number>;
    computeHot: boolean;
}
interface TagQueryData {
    provinceList: Array<Province>;
    cityList: Array<City>;
}
interface ResponseData {
    cityPremiseVOList: Array<City>;
    coveredHouseholdNum: number;
    coveredPeopleNum: number;
    houseDetailVO: object;
    peopleDetailVO: object;
    pointDetailVO: object;
    pointNum: number;
    premiseDetailVO: object;
    premisesNum: number;
    provincePremisesList: Array<Province>;
};

const router = useRouter();
const route = useRoute();
const storeApp = computed(() => {
    return store.state.app;
});
const storeHome = storeApp.value.home;
const storeSelectByTag = storeApp.value.selectByTag;
const isFromForgetting = +(route.query.isFromForgetting as string) === 1;
console.log('map-isfromForgetting:',isFromForgetting);
const tagQueryForm = reactive<TagQueryForm>({
    projectId: storeHome.projectId,
    cityCodes: [],
    tags: [],
    premisesTypes: [],
    premisesPrices: [],
    premisesAges: [],
    inHouseRates: [],
    parkingNums: [],
    propertyFees: [],
    computeHot: true,
});
const buildingTagList = computed(() => {
    return tagQueryForm.premisesTypes.concat(tagQueryForm.premisesPrices, tagQueryForm.premisesAges, tagQueryForm.inHouseRates, tagQueryForm.parkingNums, tagQueryForm.propertyFees);
});
const tagQueryData = reactive<TagQueryData>({
    provinceList: [],
    cityList: [],
});
const mediaResourceInfo = reactive<MediaResourceInfo>({
    premisesNum: 0,
    pointNum: 0,
    coveredHouseholdNum: 0,
    coveredPeopleNum: 0,
    screen: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
    lcd: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
    frame: {
        premisesNum: 0,
        pointNum: 0,
        coveredHouseholdNum: 0,
        coveredPeopleNum: 0,
    },
});
const responseData = reactive<ResponseData>({
    cityPremiseVOList: [],
    coveredHouseholdNum: 0,
    coveredPeopleNum: 0,
    houseDetailVO: {},
    peopleDetailVO: {},
    pointDetailVO: {},
    pointNum: 0,
    premiseDetailVO: {},
    premisesNum: 0,
    provincePremisesList: [],
});

const makeQueryData = () => {
    let provinceList = responseData.provincePremisesList || [] as Array<Province>;
    let cityList = responseData.cityPremiseVOList || [] as Array<City>;
    cityList = cityList.map((city: City) => {
        let cityPremisesList = city.premisesList || [];
        cityPremisesList = cityPremisesList.map((cityPremises: Premises) => {
            cityPremises.id = cityPremises.premisesId;
            cityPremises.name = cityPremises.premisesName;
            return cityPremises;
        });
        return city;
    });
    // 如果获取了多个省的数据时，默认展示省，如果只获取了一个省的数据，默认展示城市
    if (provinceList.length > 1) {
        for (let i = 0; i < provinceList.length; i++) {
            const province = provinceList[i];
            province.cityList = [];
            for (let j = 0; j < cityList.length; j++) {
                const city = cityList[j];
                if (city.provinceCode === province.provinceCode) {
                    province.cityList.push(city);
                }
            }
        };
        tagQueryData.provinceList = provinceList;
    } else {
        tagQueryData.cityList = cityList;
    }
};
const makeMediaResourceInfo = () => {
    mediaResourceInfo.premisesNum = responseData.premisesNum;
    mediaResourceInfo.pointNum = responseData.pointNum;
    mediaResourceInfo.coveredHouseholdNum = responseData.coveredHouseholdNum;
    mediaResourceInfo.coveredPeopleNum = responseData.coveredPeopleNum;
    mediaResourceInfo.screen = {
        premisesNum: responseData.premiseDetailVO ? responseData.premiseDetailVO.screenPremiseNum : 0,
        pointNum: responseData.pointDetailVO ? responseData.pointDetailVO.screenPointNum : 0,
        coveredHouseholdNum: responseData.houseDetailVO ? responseData.houseDetailVO.screenCoveredHouseholdNum : 0,
        coveredPeopleNum: responseData.peopleDetailVO ? responseData.peopleDetailVO.screenCoveredPeopleNum : 0,
    };
    mediaResourceInfo.lcd = {
        premisesNum: responseData.premiseDetailVO ? responseData.premiseDetailVO.lcdPremiseNum : 0,
        pointNum: responseData.pointDetailVO ? responseData.pointDetailVO.lcdPointNum : 0,
        coveredHouseholdNum: responseData.houseDetailVO ? responseData.houseDetailVO.lcdCoveredHouseholdNum : 0,
        coveredPeopleNum: responseData.peopleDetailVO ? responseData.peopleDetailVO.lcdCoveredPeopleNum : 0,
    };
    mediaResourceInfo.frame = {
        premisesNum: responseData.premiseDetailVO ? responseData.premiseDetailVO.framePremiseNum : 0,
        pointNum: responseData.pointDetailVO ? responseData.pointDetailVO.framePointNum : 0,
        coveredHouseholdNum: responseData.houseDetailVO ? responseData.houseDetailVO.frameCoveredHouseholdNum : 0,
        coveredPeopleNum: responseData.peopleDetailVO ? responseData.peopleDetailVO.frameCoveredPeopleNum : 0,
    };
};
const getQueryData = async (type: string = 'tag') => {
    showLoading();
    try {
        const params = {
            ...tagQueryForm,
        };
        let res;
        if (type === 'buildingTag') {
            res = await getBuildingTagQueryData(params);
        } else {
            res = await getTagQueryData(params);
        }
        Object.assign(responseData, res);
        makeQueryData();
        makeMediaResourceInfo();
    } catch(error) {
      console.error(error);
    } finally {
        clearLoading();
    }
};
const getCityPremisesList = (city: { cityCode: string; cityName: string; }) => {
    // 在地图页面，当城市下面的楼盘列表的长度为0时，会触发获取城市楼盘列表的逻辑
    // 为了避免已经获取过该城市的楼盘列表，但该城市的楼盘列表就是为空时，反复调用接口，添加 currentCityCode 与 city.cityCode 的比较判断
    const currentCityCode = tagQueryForm.cityCodes[0] || '';
    if (currentCityCode === city.cityCode) {
        return;
    }
    tagQueryForm.cityCodes = [city.cityCode];
    if (buildingTagList.value.length) {
        getQueryData('buildingTag');
    } else {
        getQueryData();
    }
};

const buildingTagPopupShow = ref<boolean>(false);
const switchBuildingTagPopup = () => {
    buildingTagPopupShow.value = !buildingTagPopupShow.value;
};
const onBuildingTagConfirm = (buildingTag: object) => {
    // 只有一个城市的数据的时候，默认展示海量点热力图，此时需要传城市code给后端，不将城市code清空
    if (tagQueryData.cityList.length !== 1) {
        tagQueryForm.cityCodes = [];
    }
    Object.assign(tagQueryForm, buildingTag);
    getQueryData('buildingTag');
    switchBuildingTagPopup();
};
const goPre = () => {
    router.back();
};
const goNext = () => {
    router.push({
        name: 'productsSelectByTagStrategyCheck',
        query:{
            isFromForgetting :+isFromForgetting
        }
    });
};
const makeQueryTagData = () => {
    if (storeSelectByTag.cityCodeList.length) {
        tagQueryForm.tags.push(storeSelectByTag.cityCodeList.join(','));
    }
    for (let key in storeSelectByTag.customKeyTag) {
        const tagList = storeSelectByTag.customKeyTag[key];
        const tagCodeList = tagList.map((tag: Tag) => {
            return tag.id;
        });
        if (tagCodeList.length) {
            tagQueryForm.tags.push(tagCodeList.join(','));
        }
    }
    if (storeSelectByTag.preferenceIdList.length) {
        tagQueryForm.tags.push(storeSelectByTag.preferenceIdList.join(','));
    }
    if (storeSelectByTag.currentCheckObjTag.length) {
        const currentCheckObjTagCodeList = storeSelectByTag.currentCheckObjTag.map((tag: Tag) => {
            return tag.id;
        });
        tagQueryForm.tags.push(currentCheckObjTagCodeList.join(','));
    }
};

onMounted(() => {
    makeQueryTagData();
    getQueryData();
});
</script>

<style lang="scss" scoped>
.page {
    position: relative;

    .build-tag-btn {
        width: 122px;
        height: 26px;
        font-size: 12px;
        font-weight: 500;
        color: #333;
        background: #fff;
        box-shadow: 0 0 4px 0 #0000000f;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: calc(12px + env(safe-area-inset-top));
        top: calc(12px + contain(safe-area-inset-top));
        left: 12px;
        z-index: 9;

        .icon-building {
            width: 14px;
            height: 14px;
            margin-right: 4px;
        }

        .icon-arrow {
            width: 8px;
            height: 8px;
            margin-left: 4px;
        }
    }

    .page-bottom {
        width: 100%;
        background: #fff;
        border-radius: 12px 12px 0 0;
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 8;
        padding-bottom: env(safe-area-inset-bottom);
        padding-bottom: contain(safe-area-inset-bottom);
    }

    .btn-box {
        width: 100%;
        height: 50px;
        background: #fff;
        padding: 0 12px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        border-top: 0.5px solid #f4f4f4;

        .pre-btn {
            width: 120px;
            height: 38px;
            line-height: 38px;
            background: #ffffff;
            border: 0.5px solid #e60044;
            border-radius: 6px;
            font-weight: 400;
            font-size: 14px;
            color: #e60044;
            text-align: center;
            margin-right: 12px;
        }
        .next-btn {
            width: calc(100% - 120px);
            height: 38px;
            line-height: 38px;
            background: #e60044;
            border: 0.5px solid #e60044;
            border-radius: 6px;
            font-weight: 600;
            font-size: 14px;
            color: #ffffff;
            text-align: center;
        }
    }
}
</style>
